import queryString from 'query-string';
import fetch from 'isomorphic-unfetch';
import fetchJsonp from 'fetch-jsonp';
import md5 from 'md5';
import SysUtil from './SysUtil';
import Config from './Config';

/**
 * 网络请求
 * 注：缓存的部分请查阅文章：https://undefinedblog.com/how-to-intercept-fetch/
 */

export default class HttpClient 
{
    /*
     * 禹州
     */
    // 门户
    static get HOST_PORTAL()
    {
        return Config.instance.hostPortal;
    }
    //电商标准接口
    static get HOST_E_BUSINESS()
    {
        return Config.instance.hostEBusiness;
    }
    //电商统一支付平台
    static get HOST_E_PAYMENT()
    {
        return Config.instance.hostEPayment;
    }
    
    //微信后台域名
    static get HOST_WECHAT_SERVER()
    {
        return Config.instance.hostWechatServer;
    }

    //微信接口
    static WECHAT_HANDLER       = HttpClient.HOST_WECHAT_SERVER + '/Content/Handler/WeChatHandler.ashx';

    //天气接口
    static HOST_WEATHER         = 'http://api.map.baidu.com/telematics/v3/weather';

    static __APP_CODE__         = 'app';
    static __APP_KEY__          = 'd25fd167d84e4170be6da3666cbd457e';
    
   

    static getFromPortal(portalApi: any, kvDict: any = undefined, cachedCallback: any = undefined)
    {
        return this.getFromPortalWithUrl(this.HOST_PORTAL,portalApi,kvDict,cachedCallback);
    }
    static getFromPortalWithUrl(url: string = this.HOST_PORTAL,portalApi: any, kvDict: any = undefined, cachedCallback: any = undefined)
    {
        let appData = this._getAppData(portalApi.pageCode, portalApi.apiCode);

        kvDict = kvDict ? kvDict : { '_empty_': '_empty_' };
        kvDict.Sign = md5(appData + this._concatParameters(kvDict)).toUpperCase();
        kvDict.AppData = appData;

        return this.getData(url + portalApi.url, kvDict, cachedCallback);
    }
    // Get 请求
    static getData(url: string, kvDict: any = undefined, cachedCallback: any = undefined) 
    {
        return new Promise((resolve, reject) => {
            if (!url || url === undefined) {
                reject('无效的请求参数: url: ' + url);
            }
            else {
                url = this._concatUrlAndParameters(url, kvDict);
                if (cachedCallback) {
                    this._responseWithCache(url, cachedCallback);
                }
                resolve({ url: url });
            }
        }).then((options) => {
            return fetch(options.url).then((resp) => {
                if (resp && cachedCallback) {
                    resp.clone().text().then((text) => {
                        this._cacheResponse(url, text);
                    });
                }
                return resp;
            });
        });
    }

    // jsonp 请求
    static getDataWithJsonp(url: string, kvDict: any = undefined, cachedCallback: any = undefined) 
    {
        return new Promise((resolve, reject) => {
            if (!url || url === undefined) {
                reject('无效的请求参数: url: ' + url);
            }
            else {
                url = this._concatUrlAndParameters(url, kvDict);
                if (cachedCallback) {
                    this._responseWithCache(url, cachedCallback);
                }
                resolve({ url: url });
            }
        }).then((options) => {
            return fetchJsonp(options.url).then((resp) => resp.json());
        });
    }
    static postToPortalWithUrl(url: string = this.HOST_PORTAL ,portalApi: any, kvDict: any = undefined, cachedCallback: any = undefined, parametersAppendWithUrl: boolean = false, fileList: Array = undefined)
    {
        let appData = this._getAppData(portalApi.pageCode, portalApi.apiCode);

        kvDict = kvDict ? kvDict : { '_empty_': '_empty_' };
        kvDict.Sign = md5(appData + this._concatParameters(kvDict)).toUpperCase();
        kvDict.AppData = appData;

        if(fileList && fileList.length > 0)
        {
            // return this.postDataWithFile(url + portalApi.url, kvDict, parametersAppendWithUrl, fileList);
        }
        else
        {
            return this.postData(url + portalApi.url, kvDict, cachedCallback, parametersAppendWithUrl, fileList);
        }
    }
    // Post 请求
    static postData(url: string, kvDict: any = undefined, cachedCallback: any = undefined, parametersAppendWithUrl: boolean = false) 
    {
        kvDict = kvDict ? kvDict : { '__empty__': '__empty__' };
        let cachedUrl;
        return new Promise((resolve, reject) => {
            if (!url || url === undefined) 
            {
                reject('无效的请求参数: url: ' + url);
            }
            else 
            {
                if (!parametersAppendWithUrl) 
                {
                    if (cachedCallback) 
                    {
                        cachedUrl = url + (kvDict ? JSON.stringify(kvDict) : '');
                        this._responseWithCache(cachedUrl, cachedCallback);
                    }
                    let body = this._concatParameters(kvDict);
                    resolve({ url: url, body: body });
                }
                else 
                {
                    url = this._concatUrlAndParameters(url, kvDict);
                    if (cachedCallback) 
                    {
                        cachedUrl = url + (kvDict ? JSON.stringify(kvDict) : '');
                        this._responseWithCache(cachedUrl, cachedCallback);
                    }
                    resolve({ url: url });
                }
            }
        }).then((options) => {
            return fetch(options.url, {
                method: 'POST',
                body: options.body,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            }).then((resp) => {
                if (resp && cachedCallback && cachedUrl) 
                {
                    resp.clone().text().then((text) => {
                        this._cacheResponse(cachedUrl, text);
                    });
                }
                return resp;
            });
        });
    }
    static _cacheResponse(url: string, result: string) 
    {
        if (!url || !result) 
        {
            return;
        }
    }
    static _responseWithCache(url: string, cachedCallback: any) 
    {
        if (!url || !cachedCallback) 
        {
            return;
        }
    }

    static _concatUrlAndParameters(url: string, kvDict: any = undefined) 
    {
        if (!kvDict) 
        {
            return url;
        }
        let searchParams = {};
        for (let key in kvDict) 
        {
            let obj = kvDict[key];
            if (obj instanceof Object) 
            {
                searchParams[key] = JSON.stringify(obj);
            }
            else 
            {
                searchParams[key] = obj;
            }
        }
        let params = queryString.stringify(searchParams);
        // console.log('hello ' + params);
        url += (url.indexOf('?') === -1 ? '?' : '&') + params;
        return url;
    }

    static _concatParameters(kvDict: any = undefined) 
    {
        if (!kvDict) 
        {
            return '';
        }
        let searchParams = {};
        for (let key in kvDict) 
        {
            let obj = kvDict[key];
            if (obj instanceof Object) 
            {
                searchParams[key] = JSON.stringify(obj);
            }
            else 
            {
                searchParams[key] = obj;
            }
        }
        let params = queryString.stringify(searchParams);
        // console.log('hello ' + params);
        return params;
    }

    static _getAppData(pageCode: string, apiCode: string) {
        let userId = SysUtil.getUserId();
        userId = userId ? userId : '';
        return {
            AppCode: this.__APP_CODE__,
            AppKey: this.__APP_KEY__,
            PageCode: pageCode,
            ApiCode: apiCode,
            LoginUserID: userId,
            ClientType: '2',
            TimeStamp: new Date().getTime(),
        };
    }
}
